<template>
  <div class="box">
    <div class="box-content">
      <div class="search">
        <div class="search-btn" style="font-size: 18px; font-weight: 600; margin-left: 30px"
          >{{ info.gradeAndClassName }}
        </div>
        <div class="search-btn" style="display: flex; align-items: center">
          <!-- <div v-if="dormitoryIsAdmin === true" class="btn-click">
            <a-button
              type="primary"
              :disabled="unAllocationNum <= 0 ? true : false"
              @click="onAllocation()"
              >宿舍分配</a-button
            >
          </div> -->
          <a-button
            v-if="dormitoryIsAdmin === true"
            type="primary"
            style="margin: 0 0 0 16px"
            ghost
            :disabled="unAllocationNum < 0 ? true : false"
            @click="classCheckOut"
            >班级退宿</a-button
          >
          <a-button
            style="margin: 0 0 0 16px"
            type="primary"
            html-type="submit"
            ghost
            @click="getClassExport"
          >
            <template #icon><ToTopOutlined /></template>
            导出
          </a-button>
        </div>
      </div>
      <div v-if="info.noStatusStuList" class="deduct-points">
        <div class="small-title"
          >成员（ {{ info.noStatusStuList ? info.noStatusStuList.length : 0 }}人）</div
        >
        <div class="deduct-points-content">
          <div v-for="member in info.noStatusStuList" :key="member.id" class="content-details">
            <img v-if="member.studentAvatar" :src="member.studentAvatar" alt="" class="head" />
            <img v-else src="@/assets/images/accommodation/icon_big.png" alt="" class="head" />
            <div class="infos">
              {{ member.studentName }}
              <img
                v-if="member.gender === '0'"
                src="@/assets/images/accommodation/class_icon_girl.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/class_icon_boy.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <div v-if="unAllocationNum < 0" class="deduct-points">
        <div class="small-title">住宿（--人）</div>
      </div>
      <div v-if="info.allocationStuList" class="deduct-points">
        <div class="small-title">住宿（已分配 {{ info.allocationStuList.length }} 人）</div>
        <div class="deduct-points-content">
          <div
            v-for="(allocated, index) in info.allocationStuList"
            :key="index"
            class="content-details"
          >
            <img
              v-if="allocated.studentAvatar"
              :src="allocated.studentAvatar"
              alt=""
              class="head"
            />
            <img v-else src="@/assets/images/accommodation/icon_big.png" alt="" class="head" />
            <div class="infos">
              {{ allocated.studentName }}
              <img
                v-if="allocated.gender === '女'"
                src="@/assets/images/accommodation/class_icon_girl.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/class_icon_boy.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <div v-if="info.unAllocationStuList" class="deduct-points">
        <div class="small-title">住宿（未分配 {{ info.unAllocationStuList.length }} 人）</div>
        <div class="deduct-points-content">
          <div
            v-for="unAllocation in info.unAllocationStuList"
            :key="unAllocation.id"
            class="content-details"
          >
            <img
              v-if="unAllocation.studentAvatar"
              :src="unAllocation.studentAvatar"
              alt=""
              class="head"
            />
            <img v-else src="@/assets/images/accommodation/icon_big.png" alt="" class="head" />
            <div class="infos">
              {{ unAllocation.studentName }}
              <img
                v-if="unAllocation.gender === '女'"
                src="@/assets/images/accommodation/class_icon_girl.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/class_icon_boy.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <div v-if="info.externStuList" class="deduct-points">
        <div class="small-title"
          >走读（{{ info.externStuList ? info.externStuList.length : 0 }}人 ）</div
        >
        <div class="deduct-points-content">
          <div v-for="extern in info.externStuList" :key="extern.id" class="content-details">
            <img v-if="extern.studentAvatar" :src="extern.studentAvatar" alt="" class="head" />
            <img v-else src="@/assets/images/accommodation/icon_big.png" alt="" class="head" />
            <div class="infos">
              {{ extern.studentName }}
              <img
                v-if="extern.gender === '女'"
                src="@/assets/images/accommodation/class_icon_girl.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/class_icon_boy.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <!-- <div v-else class="deduct-points">
        <div class="small-title">走读（--人）</div>
      </div> -->
      <div v-if="unAllocationNum == 0 || info.girlDormitory" class="deduct-points">
        <div class="small-title">女生宿舍</div>
        <div class="dormitory-info">
          <div v-for="girl in info.girlDormitory" :key="girl.id" class="dormitory-info-div">
            <div class="info-con">
              <div class="top">
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  placement="topLeft"
                  :title="girl.roomName"
                >
                  {{ girl.roomName }}
                </Tooltip>
              </div>
              <div class="content">
                <a-table
                  :columns="columns"
                  :data-source="girl.studentList"
                  :row-key="record => record.bedNumber"
                  :pagination="false"
                  :scroll="girl.studentList.length > 6 ? { y: 300 } : 'false'"
                >
                </a-table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="unAllocationNum === 0 || info.boyDormitory" class="deduct-points">
        <div class="small-title">男生宿舍</div>
        <div class="dormitory-info">
          <div v-for="boy in info.boyDormitory" :key="boy.id" class="dormitory-info-div">
            <div class="info-con">
              <div class="top">
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  placement="topLeft"
                  :title="boy.roomName"
                >
                  {{ boy.roomName }}
                </Tooltip>
              </div>
              <div class="content">
                <a-table
                  :columns="columns"
                  :data-source="boy.studentList"
                  :row-key="record => record.bedNumber"
                  :pagination="false"
                  :scroll="boy.studentList.length > 6 ? { y: 300 } : 'false'"
                >
                </a-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 退宿 提示框 -->
    <my-dialog
      :dialog-state="checkOut.visible"
      :dialog-title="checkOut.title"
      :dialog-width="checkOut.width"
      :icon-type="checkOut.iconType"
      :btn-loading="btnLoading"
      @handleCancel="handleCancelTwo"
      @handleOk="checkOuts"
    >
      <template v-slot:location>
        <div class="checkOutStyle">
          <img src="@/assets/images/accommodation/drawable-xxxhdpi_popu_icon_warn.png" alt="" />
          <span>{{ text }}</span>
        </div>
        <p v-if="show" class="checkOut-notes"
          >注：此动作将会清除已选内容所有住宿信息，请谨慎操作。</p
        >
      </template>
    </my-dialog>
    <!-- 宿舍分配 -->
    <my-dialog
      :dialog-state="dormitoryPrecise.visible"
      :dialog-title="dormitoryPrecise.title"
      :btn-state="dormitoryPrecise.state"
      :dialog-width="dormitoryPrecise.width"
      :icon-type="dormitoryPrecise.iconType"
      @handleCancel="handleCancel()"
      @handleOk="handleOk()"
    >
      <template v-slot:location>
        <div class="campus">{{ className }}</div>
        <div class="content">
          <div class="option">
            <a-tabs v-model:activeKey="dialogActiveKey" class="z-tab-box-padding">
              <a-tab-pane
                :key="sexChoice[0].dataIndex"
                :tab="sexChoice[0].title + '(' + sexChoice[0].num + ')'"
              >
                <div style="overflow: auto; height: 400px">
                  <a-menu v-model:openKeys="openKeysGirl" mode="inline" style="width: 99%">
                    <a-sub-menu v-for="(item, index) in dormitoryListGirl" :key="index">
                      <template #title> {{ item.name }} </template>
                      <a-sub-menu
                        v-for="(elem, key) in item.storeyList"
                        :key="`${index}-${key}`"
                        :title="`${elem.id}楼`"
                        :disabled="item.existStoreyList?.indexOf(elem.id) === -1"
                        @titleClick="onTotal(item.id, elem.id, index, key, 0)"
                      >
                        <template
                          v-if="item.existStoreyList?.indexOf(elem.id) === -1"
                          #expandIcon
                        ></template>
                        <a-sub-menu
                          v-for="(room, i) in elem.roomList"
                          :key="`${index}-${key}-${i}`"
                          @titleClick="onBedNum(room)"
                        >
                          <template #title>
                            <a-checkbox
                              v-model:checked="room.checked"
                              :indeterminate="checkboxStyIdent(room)"
                              style="margin-right: 5px"
                              @click.stop
                              @change="onChangeRoomChecked(room, 'girl')"
                            />
                            <Tooltip
                              :overlay-style="{ whiteSpace: 'normal' }"
                              :get-popup-container="
                                triggerNode => {
                                  return triggerNode.parentNode || document.body;
                                }
                              "
                              placement="topLeft"
                              :title="room.roomName"
                            >
                              {{ room.roomName }}
                            </Tooltip>
                          </template>
                          <div style="padding: 0 0 10px 80px">
                            <div class="checkBox">
                              <Row :gutter="[0, 16]">
                                <Col v-for="(num, n) in room.bedNumberList" :key="n" :span="24">
                                  <div>
                                    <a-checkbox
                                      v-model:checked="num.checked"
                                      :disabled="onDisabledBedGirl(num)"
                                      style="margin-right: 5px"
                                      @change="checkboxChange(room, num, 'girl')"
                                    />
                                    <span> {{ num.bedNumber }} 号床 </span>
                                  </div>
                                </Col>
                              </Row>
                            </div>
                          </div>
                        </a-sub-menu>
                      </a-sub-menu>
                    </a-sub-menu>
                  </a-menu>
                </div>
              </a-tab-pane>
              <a-tab-pane
                :key="sexChoice[1].dataIndex"
                :tab="sexChoice[1].title + '(' + sexChoice[1].num + ')'"
              >
                <div style="overflow: auto; height: 400px">
                  <a-menu v-model:openKeys="openKeysBoy" mode="inline" style="width: 99%">
                    <a-sub-menu v-for="(item, index) in dormitoryListBoy" :key="index">
                      <template #title> {{ item.name }} </template>
                      <!-- 男生 -->
                      <a-sub-menu
                        v-for="(elem, key) in item.storeyList"
                        :key="`${index}-${key}`"
                        :title="`${elem.id}楼`"
                        :disabled="item.existStoreyList?.indexOf(elem.id) === -1"
                        @titleClick="onTotal(item.id, elem.id, index, key, 1)"
                      >
                        <template
                          v-if="item.existStoreyList?.indexOf(elem.id) === -1"
                          #expandIcon
                        ></template>
                        <a-sub-menu
                          v-for="(room, i) in elem.roomList"
                          :key="`${index}-${key}-${i}`"
                          @titleClick="onBedNum(room)"
                        >
                          <template #title>
                            <a-checkbox
                              v-model:checked="room.checked"
                              :indeterminate="checkboxStyIdent(room)"
                              style="margin-right: 5px"
                              @click.stop
                              @change="onChangeRoomChecked(room, 'boy')"
                            />
                            <Tooltip
                              :overlay-style="{ whiteSpace: 'normal' }"
                              :get-popup-container="
                                triggerNode => {
                                  return triggerNode.parentNode || document.body;
                                }
                              "
                              placement="topLeft"
                              :title="room.roomName"
                            >
                              {{ room.roomName }}
                            </Tooltip>
                          </template>
                          <div style="padding: 0 0 10px 80px">
                            <div class="checkBox">
                              <Row :gutter="[0, 16]">
                                <Col v-for="(num, n) in room.bedNumberList" :key="n" :span="24">
                                  <div>
                                    <a-checkbox
                                      v-model:checked="num.checked"
                                      :disabled="onDisabledBedBoy(num)"
                                      style="margin-right: 5px"
                                      @change="checkboxChange(room, num, 'boy')"
                                    />

                                    <span>{{ num.bedNumber }} 号床 </span>
                                  </div>
                                </Col>
                              </Row>
                            </div>
                          </div>
                        </a-sub-menu>
                      </a-sub-menu>
                    </a-sub-menu>
                  </a-menu>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="detailsStudent">
            <div class="info">详情</div>
            <div v-if="dialogActiveKey === '0'" class="info-content">
              <ul class="checkBox">
                <li v-for="(item, i) in girlLists" :key="i" :span="12">
                  <a-checkbox
                    v-model:checked="item.checked"
                    :checked="item.checked"
                    :disabled="item.disabled"
                    @change="checkboxChangeGirl(item)"
                  >
                    <img
                      v-if="item.studentAvatar"
                      :src="item.studentAvatar"
                      alt=""
                      style="width: 32px; height: 32px; border-radius: 50%"
                    />
                    <img v-else src="@/assets/images/accommodation/icon_mrtx.png" alt="" />
                    <span class="name">{{ item.studentName }}</span>
                  </a-checkbox>
                </li>
              </ul>
            </div>
            <div v-else class="info-content">
              <!-- <a-checkbox-group v-model:value="checkedKeysBoy"> -->
              <ul class="checkBox">
                <li v-for="(item, i) in boyList" :key="i" :span="12">
                  <a-checkbox
                    v-model:checked="item.checked"
                    :checked="item.checked"
                    :disabled="item.disabled"
                    @change="checkboxChangeBoy(item)"
                  >
                    <img
                      v-if="item.studentAvatar"
                      :src="item.studentAvatar"
                      alt=""
                      style="width: 32px; height: 32px; border-radius: 50%"
                    />
                    <img v-else src="@/assets/images/accommodation/icon_mrtx.png" alt="" />
                    <span class="name">{{ item.studentName }}</span>
                  </a-checkbox>
                </li>
              </ul>
              <!-- </a-checkbox-group> -->
            </div>
          </div>
        </div>
      </template>
    </my-dialog>
  </div>
</template>
<script setup>
import { onMounted, ref, reactive, computed, watch } from 'vue';
import {
  classStudentDetails,
  batchCheckout,
  classExport,
  exactAssignDormitory,
  getDormitorySexList,
  getDormitoryRoom,
  getRoomBedInfo,
  getUnAllocationClassStudentId
} from '@/api/classManage';
import { message, Row, Col, Tooltip } from 'ant-design-vue';
import { ToTopOutlined } from '@ant-design/icons-vue';
import MyDialog from '@/components/dialog/index.vue';

import { useRouter, useRoute } from 'vue-router';
import { debounce } from '@/utils/debounce.js';
const route = useRoute();
const router = useRouter();
let classId = ref();
let className = ref();
const unAllocationNum = ref(); // 分配状态
const dormitoryIsAdmin = ref(false);
onMounted(async () => {
  if (localStorage.getItem('dormitoryIsAdmin') * 1 === 0) {
    dormitoryIsAdmin.value = true;
  } else {
    dormitoryIsAdmin.value = false;
  }

  console.log('班级详情是不是管理员', dormitoryIsAdmin.value);
  if (route.query.id) {
    classId.value = router.currentRoute.value.query.id;
    className.value = route.query.className; // 班级名称
    await getStudentInfo(classId.value);
  } else {
    router.push('/admin/classInfo');
  }
  let bodySty = document.getElementById('myApp');
  bodySty.setAttribute('class', 'bodyStyle');
  // getClassStudentId(classId.value);
});
// const getClassStudentId = id => {
watch(
  () => route.matched,
  val => {
    if (!route.query.id) {
      router.push('/admin/classInfo');
    }
  }
);

// 多选样式标识
const checkboxStyIdent = computed(() => {
  return val => {
    let boolean = false;
    if (val.bedNumberList?.length) {
      let arrLength = JSON.parse(JSON.stringify(val.bedNumberList.length));
      let arr = val.bedNumberList.filter(v => v.checked).length;
      if (arr) {
        if (arr === arrLength) {
          boolean = false;
          val.checked = true;
        } else {
          boolean = true;
          val.checked = false;
        }
      }
    }

    return boolean;
  };
});
let dialogActiveKey = ref('0'); // 男生女生tabs
// 精准分配弹窗
const dormitoryPrecise = reactive({
  title: '宿舍分配',
  visible: false,
  width: '889px',
  iconType: 'default',
  state: '保存'
});
const sexChoice = reactive([
  {
    title: '女生',
    dataIndex: '0',
    num: 0,
    data: []
  },
  {
    title: '男生',
    dataIndex: '1',
    num: 0,
    data: []
  }
]);
let girlLists = ref([]); // 分配弹窗女生数据
let boyList = ref([]); // 分配弹窗男生数据
const info = ref([]); // 查询的所有信息
// 获取班级学生住宿详情
async function getStudentInfo(classId) {
  await classStudentDetails(classId).then(res => {
    if (res.data.code === 200) {
      info.value = res.data.data;
      console.log('班级详情--pp', info.value);
      // if (info.value.unAllocationStuList) {
      //   unAllocationNum.value = info.value.unAllocationStuList.length; // 分配状态
      // } else if (info.value.unAllocationStuList && !info.value.unAllocationStuList.length === 0) {
      //   unAllocationNum.value = 0;
      // } else {
      //   unAllocationNum.value = -1;
      // }
      if (info.value.unAllocationStuList) {
        unAllocationNum.value = info.value.unAllocationStuList.length; // 分配状态
      } else {
        if (info.value.allocationStuList) {
          unAllocationNum.value = 0;
        } else {
          unAllocationNum.value = -1;
        }
      }
    }
  });
}
// 导出
const getClassExport = debounce(function () {
  let roomIds = [];
  let girlDormitory = info.value.girlDormitory;
  let boyDormitory = info.value.boyDormitory;
  if (girlDormitory) {
    girlDormitory.forEach(item => {
      roomIds.push(item.roomId);
    });
  }
  if (boyDormitory) {
    boyDormitory.forEach(item => {
      roomIds.push(item.roomId);
    });
  }
  classExport({ classId: route.query.id, roomIds }).then(res => {
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement('a');
    document.body.appendChild(a);
    a.href = url;
    a.download = className.value + '住宿信息.xls';
    a.click();
    window.URL.revokeObjectURL(url);
  });
}, 500);
// 打开宿舍分配弹窗
const onAllocation = async () => {
  let boyData = [];
  let girlData = [];
  await getUnAllocationClassStudentId(classId.value).then(res => {
    let data = res.data.data;
    console.log(data);
    data.forEach((item, index) => {
      if (item.gender === '女') {
        console.log('女');
        item.studentList.forEach(x => {
          girlData.push({
            disabled: true,
            checked: false,
            studentName: x.studentName,
            studentAvatar: x.studentAvatar,
            studentId: x.studentId
          });
        });
      } else {
        console.log('男');
        item.studentList.forEach(x => {
          boyData.push({
            disabled: true,
            checked: false,
            studentName: x.studentName,
            studentAvatar: x.studentAvatar,
            studentId: x.studentId
          });
        });
      }
    });
  });
  console.log(boyData);
  sexChoice[0].num = girlData.length;
  sexChoice[1].num = boyData.length;
  girlLists.value = girlData;
  boyList.value = boyData;

  sexChoice[0].data = girlLists.value;
  sexChoice[1].data = boyList.value;
  getDormitoryList(0);
  getDormitoryList(1);
  dormitoryPrecise.visible = true;
};
// ------------------宿舍列表------------------
let dormitoryListGirl = ref([]); // 女生
let dormitoryListBoy = ref([]); // 男生
// 获取宿舍列表
function getDormitoryList(sex) {
  getDormitorySexList(sex).then(res => {
    if (sex === 0) {
      dormitoryListGirl.value = res.data.data;
      dormitoryListGirl.value.forEach(elem => {
        let storeyList = [];
        for (let i = 0; i < elem.totalStorey; i++) {
          let obj = {
            id: i + 1,
            roomList: []
          };
          storeyList.push(obj);
        }
        elem.storeyList = storeyList;
      });
    } else {
      dormitoryListBoy.value = res.data.data;

      dormitoryListBoy.value.forEach(elem => {
        let storeyList = [];
        for (let i = 0; i < elem.totalStorey; i++) {
          let obj = {
            id: i + 1,
            roomList: []
          };
          storeyList.push(obj);
        }
        elem.storeyList = storeyList;
      });
    }
  });
}
// 男女生楼层点击事件
const onTotal = (dormitoryId, storey, index, key, sex) => {
  getDormitoryRoomList(dormitoryId, storey, index, key, sex);
};
// 获取楼层房间列表
function getDormitoryRoomList(dormitoryId, storey, index, key, sex) {
  getDormitoryRoom(dormitoryId, storey, sex).then(res => {
    let data = [];
    res.data.data.forEach(item => {
      data.push({
        checked: false, // 选中状态
        disabled: false, // 是否禁选
        airBedNumber: item.airBedNumber, // 空床数
        bedNum: item.bedNum, // 床位数
        dormitoryId: item.dormitoryId, // 宿舍楼ID
        dormitoryName: item.dormitoryName, // 宿舍楼名称
        genderAttribute: item.genderAttribute, // 宿舍楼属性
        roomId: item.id, // 房间ID
        lou: storey, // 楼层
        roomName: item.name, // 房间名称
        occupancyNumber: item.occupancyNumber,
        roomPhone: item.roomPhone,
        schoolId: item.schoolId,
        storey: item.storey,
        tenantId: item.tenantId,
        useState: item.useState,
        data: [],
        bedNumberList: []
      });
    });
    if (sex === 0) {
      dormitoryListGirl.value[index].storeyList[key].roomList = data;
    } else {
      dormitoryListBoy.value[index].storeyList[key].roomList = data;
    }
  });
}
// 男生树checkbo事件
const columns = [
  {
    title: '床号',
    dataIndex: 'bedNumber',
    key: 'bedNumber'
  },
  {
    title: '姓名',
    dataIndex: 'studentName',
    key: 'studentName'
  }
];
const checkOut = reactive({
  title: '温馨提示',
  visible: false,
  width: '328px',
  iconType: 'default',
  state: true
});

function classCheckOut() {
  checkOut.visible = true;
  checkOut.state = true;
}

let text = ref('是否清空当前班级住宿信息？');
const checkOuts = debounce(function () {
  btnLoading.value = true;
  console.log(checkOut.state, 'checkOut.state');
  if (checkOut.state) {
    batchCheckout([classId.value]).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg);
        checkOut.visible = false;
        btnLoading.value = false;
        router.push('/admin/classInfo');
      } else {
        text.value = res.data.msg;
        btnLoading.value = false;
        checkOut.state = false;
      }
    });
    text.value = '是否确定对所选信息退宿？';
  } else {
    text.value = '是否确定对所选信息退宿？';
    checkOut.visible = false;
    btnLoading.value = false;
  }
}, 500);
// 退宿弹窗取消
const handleCancelTwo = () => {
  checkOut.visible = false;
  btnLoading.value = false;
};
/** ******************************************************************* */
// 男生/女生菜单展开
const openKeysGirl = ref([]);
const openKeysBoy = ref([]);
// 分配弹窗取消事件
const handleCancel = () => {
  openKeysGirl.value = [];
  openKeysBoy.value = [];
  dormitoryPrecise.visible = false;
};
// 女生/男生选中的床位
const girlBedChesked = ref([]); // 女生已选择床位
const girlBedCheskedLehgth = computed(() => girlBedChesked.value.length);
watch(girlBedCheskedLehgth, () => {
  let girlListsLength = girlLists.value.filter(elem => elem.checked).length;
  if (girlBedChesked.value.length > girlListsLength) {
    girlLists.value.forEach(elem => {
      elem.disabled = false;
    });
  }
  if (
    girlBedChesked.value.length &&
    girlListsLength &&
    girlBedChesked.value.length === girlListsLength
  ) {
    girlLists.value.forEach(elem => {
      if (!elem.checked) elem.disabled = true;
    });
  }
  if (!girlBedChesked.value.length) {
    girlLists.value.forEach(elem => {
      elem.disabled = true;
    });
  }
});
const boyBedChesked = ref([]); // 男生已选择床位
const boyBedCheskedLehgth = computed(() => boyBedChesked.value.length);
watch(boyBedCheskedLehgth, () => {
  let boyListLength = boyList.value.filter(elem => elem.checked).length;
  if (boyBedChesked.value.length > boyListLength) {
    boyList.value.forEach(elem => {
      elem.disabled = false;
    });
  }
  if (boyBedChesked.value.length && boyListLength && boyBedChesked.value.length === boyListLength) {
    boyList.value.forEach(elem => {
      if (!elem.checked) elem.disabled = true;
    });
  }
  if (!boyBedChesked.value.length) {
    boyList.value.forEach(elem => {
      elem.disabled = true;
    });
  }
});
// 女生/男生床位禁用
const onDisabledBedGirl = data => {
  let boolean = false;
  let onCheckedBedStudentId = girlBedChesked.value.filter(x => x.studentId).map(x => x.bedId);
  if (onCheckedBedStudentId.indexOf(data.bedId) !== -1) {
    boolean = true;
  } else {
    boolean = false;
  }
  return boolean;
};
const onDisabledBedBoy = data => {
  let boolean = false;
  let onCheckedBedStudentId = boyBedChesked.value.filter(x => x.studentId).map(x => x.bedId);
  if (onCheckedBedStudentId.indexOf(data.bedId) !== -1) {
    boolean = true;
  } else {
    boolean = false;
  }
  return boolean;
};
// 选择女生回调
const checkboxChangeGirl = data => {
  console.log(data);
  sexChoice[0].num = girlLists.value.filter(elem => !elem.checked).length;
  if (girlLists.value.filter(elem => elem.checked).length === girlBedChesked.value.length) {
    girlLists.value.forEach(elem => {
      if (!elem.checked) elem.disabled = true;
    });
  } else {
    girlLists.value.forEach(elem => {
      elem.disabled = false;
    });
  }
  if (data.checked) {
    for (let v of girlBedChesked.value) {
      if (!v.studentId) {
        v.studentId = data.studentId;
        break;
      }
    }
  } else {
    girlBedChesked.value.forEach(elem => {
      if (elem.studentId === data.studentId) elem.studentId = undefined;
    });
  }
  console.log(girlBedChesked.value);
};
// 男生checkbo事件
const checkboxChangeBoy = data => {
  console.log(data);
  console.log(boyList.value);
  sexChoice[1].num = boyList.value.filter(elem => !elem.checked).length;
  if (boyList.value.filter(elem => elem.checked).length === boyBedChesked.value.length) {
    boyList.value.forEach(elem => {
      if (!elem.checked) elem.disabled = true;
    });
  } else {
    boyList.value.forEach(elem => {
      elem.disabled = false;
    });
  }
  if (data.checked) {
    for (let v of boyBedChesked.value) {
      if (!v.studentId) {
        v.studentId = data.studentId;
        break;
      }
    }
  } else {
    boyBedChesked.value.forEach(elem => {
      if (elem.studentId === data.studentId) elem.studentId = undefined;
    });
  }
  console.log(boyBedChesked.value);
};
// 选择床位回调
const checkboxChange = (room, bed, type) => {
  console.log(room, bed, type);
  if (type === 'girl') {
    if (bed.checked) {
      girlBedChesked.value.push({
        studentId: undefined,
        dormitoryId: room.dormitoryId,
        dormitoryName: room.dormitoryName,
        roomId: room.roomId,
        roomName: room.roomName,
        bedNumber: bed.bedNumber,
        bedId: bed.bedId
      });
    } else {
      girlBedChesked.value = girlBedChesked.value.filter(elem => elem.bedId !== bed.bedId);
    }
  }
  if (type === 'boy') {
    if (bed.checked) {
      boyBedChesked.value.push({
        studentId: undefined,
        dormitoryId: room.dormitoryId,
        dormitoryName: room.dormitoryName,
        roomId: room.roomId,
        roomName: room.roomName,
        bedNumber: bed.bedNumber,
        bedId: bed.bedId
      });
    } else {
      boyBedChesked.value = boyBedChesked.value.filter(elem => elem.bedId !== bed.bedId);
    }
  }
  console.log(boyBedChesked.value);
};
// 选择房间
const onChangeRoomChecked = (room, type) => {
  if (!room.bedNumberList.length) {
    onBedNum(room);
    return false;
  }
  let bedCheckedNum = room.bedNumberList.filter(elem => elem.checked).length;
  if (room.checked) {
    onCheckedRoomAll(room, type);
  } else {
    if (bedCheckedNum < room.bedNumberList.length) {
      room.checked = true;
      onCheckedRoomAll(room, type);
      return false;
    }
    if (type === 'girl') {
      let arr = girlBedChesked.value.filter(x => x.studentId).map(x => x.bedId);
      room.bedNumberList.forEach(elem => {
        if (arr.indexOf(elem.bedId) === -1) {
          elem.checked = false;
        } else {
          elem.checked = true;
        }
      });

      let list = room.bedNumberList.filter(x => !x.checked).map(x => x.bedId);
      let newList = [];
      girlBedChesked.value.forEach(elem => {
        if (list.indexOf(elem.bedId) === -1) newList.push(elem);
      });
      girlBedChesked.value = newList;
    }
    if (type === 'boy') {
      let arr = boyBedChesked.value.filter(x => x.studentId).map(x => x.bedId);
      room.bedNumberList.forEach(elem => {
        if (arr.indexOf(elem.bedId) === -1) {
          elem.checked = false;
        } else {
          elem.checked = true;
        }
      });

      let list = room.bedNumberList.filter(x => !x.checked).map(x => x.bedId);
      let newList = [];
      boyBedChesked.value.forEach(elem => {
        if (list.indexOf(elem.bedId) === -1) newList.push(elem);
      });
      boyBedChesked.value = newList;
    }
  }
};
// 执行房间全选操作
const onCheckedRoomAll = (room, type) => {
  room.bedNumberList.forEach(elem => {
    elem.checked = true;
    if (type === 'girl') {
      let arr = girlBedChesked.value.map(x => x.bedId);
      if (arr.indexOf(elem.bedId) === -1) {
        girlBedChesked.value.push({
          studentId: undefined,
          dormitoryId: room.dormitoryId,
          dormitoryName: room.dormitoryName,
          roomId: room.roomId,
          roomName: room.roomName,
          bedNumber: elem.bedNumber,
          bedId: elem.bedId
        });
      }
    }
    if (type === 'boy') {
      let arr = boyBedChesked.value.map(x => x.bedId);
      if (arr.indexOf(elem.bedId) === -1) {
        boyBedChesked.value.push({
          studentId: undefined,
          dormitoryId: room.dormitoryId,
          dormitoryName: room.dormitoryName,
          roomId: room.roomId,
          roomName: room.roomName,
          bedNumber: elem.bedNumber,
          bedId: elem.bedId
        });
      }
    }
  });
};
// 获取房间中全部的床位和学生信息
const onBedNum = room => {
  console.log(room);
  if (!room.bedNumberList.length) {
    getRoomBedInfo({ id: room.roomId }).then(res => {
      res.data.data.forEach(item => {
        if (item.studentUserId) {
          console.log('已分配');
        } else {
          let obj = {
            bedId: item.id,
            bedNumber: item.bedNumber,
            checked: !!room.checked,
            disabled: false
          };
          room.bedNumberList.push(obj);
        }
      });
      if (room.genderAttribute === 0) {
        let arr = room.bedNumberList;
        let selectBedIdGirl = girlBedChesked.value.map(x => x.bedId);
        let unSelectBedIdGirl = arr.filter(x => x.checked);
        arr.forEach(elem => {
          if (selectBedIdGirl.indexOf(elem.bedId) !== -1) {
            elem.checked = true;
          }
        });
        unSelectBedIdGirl.forEach(elem => {
          if (selectBedIdGirl.indexOf(elem.bedId) === -1) {
            girlBedChesked.value.push({
              studentId: undefined,
              dormitoryId: room.dormitoryId,
              dormitoryName: room.dormitoryName,
              roomId: room.roomId,
              roomName: room.roomName,
              bedNumber: elem.bedNumber,
              bedId: elem.bedId
            });
          }
        });
      } else {
        let arr = room.bedNumberList;
        let selectBedIdboy = boyBedChesked.value.map(x => x.bedId);
        let unSelectBedIdboy = arr.filter(x => x.checked);
        arr.forEach(elem => {
          if (selectBedIdboy.indexOf(elem.bedId) !== -1) {
            elem.checked = true;
          }
        });
        unSelectBedIdboy.forEach(elem => {
          if (selectBedIdboy.indexOf(elem.bedId) === -1) {
            boyBedChesked.value.push({
              studentId: undefined,
              dormitoryId: room.dormitoryId,
              dormitoryName: room.dormitoryName,
              roomId: room.roomId,
              roomName: room.roomName,
              bedNumber: elem.bedNumber,
              bedId: elem.bedId
            });
          }
        });
      }
    });
  }
};
// 分配弹窗确定
const handleOk = () => {
  console.log(dormitoryListBoy.value);
  console.log(dormitoryListGirl.value);
  console.log(boyBedChesked.value);
  console.log(girlBedChesked.value);
  let boyList = boyBedChesked.value.filter(elem => elem.studentId);
  let girlList = girlBedChesked.value.filter(elem => elem.studentId);
  let paramsBoy = [...boyList, ...girlList];
  console.log(paramsBoy);
  if (!paramsBoy.length) {
    message.error('请选择学生进行分配');
    return false;
  }
  exactAssignDormitory(paramsBoy).then(async res => {
    if (res.data.code === 200) {
      message.success('分配成功');
      await getStudentInfo(classId.value);
      dormitoryPrecise.visible = false;
      boyBedChesked.value = [];
      girlBedChesked.value = [];
      boyList = [];
      girlList = [];
      paramsBoy = [];
      unAllocationNum.value = info.value.unAllocationStuList.length;
    }
  });
};
const btnLoading = ref(false);
</script>

<style lang="less" scoped>
.box {
  background: #f2f2f2;
  // padding: 50px 120px 24px;
  min-height: 100vh;
  min-width: 1300px;
  .box-content {
    background: #ffffff;
    border-radius: 4px;
    padding: 24px;
    .search {
      display: flex;
      justify-content: space-between;
      margin-bottom: 24px;
    }
    .deduct-points {
      margin-bottom: 32px;
      .small-title {
        font-size: 18px;
        font-family: Source Han Sans CN, Source Han Sans CN-Medium;
        font-weight: 500;
        color: #222222;
      }
      &-content {
        padding: 14px 0;
        border-radius: 4px;
        margin-top: 20px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
      }
      .content-details {
        width: 10%;
        margin-bottom: 24px;
        .head {
          margin: 0 auto;
          width: 64px;
          height: 64px;
          border-radius: 50%;
          margin-bottom: 8px;
        }
        .infos {
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          font-family: Source Han Sans CN, Source Han Sans CN-Regular;
          font-weight: 400;
          color: #222222;
        }
      }
      .dormitory-info {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        padding: 24px 0;

        .dormitory-info-div {
          width: 33%;
          display: flex;
          justify-content: center;
          .info-con {
            width: 351px;
            height: 504px;
            margin-bottom: 24px;
            background: #ffffff;
            border: 1px solid #e4b778;
            border-radius: 4px;
            .top {
              width: 349px;
              height: 60px;
              background: #fdf4ec;
              border-radius: 4px 4px 0px 0px;
              font-size: 18px;
              font-family: Source Han Sans CN, Source Han Sans CN-Medium;
              font-weight: 500;
              text-align: center;
              line-height: 60px;
              color: @color-test;
              border: none;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              padding: 0 26px;
            }
            .content {
              width: 100%;
              padding: 24px;
            }
          }
        }
      }
    }
  }
}
.checkOutStyle {
  width: 280px;
  height: 48px;
  background: #f8f8f8;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 14px;
  img {
    margin-right: 8px;
  }
}
.campus {
  // width: 64px;
  height: 24px;
  font-size: 16px;
  font-family: Source Han Sans CN, Source Han Sans CN-Regular;
  font-weight: 400;
  text-align: LEFT;
  color: #222222;
  line-height: 24px;
  margin-bottom: 16px;
}
.content {
  display: flex;
  justify-content: space-between;
  .option {
    width: 208px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    .micro-dormitory-tree
      > .micro-dormitory-tree-list
      > .micro-dormitory-tree-list-holder
      > .micro-dormitory-tree-list-holder-inner
      > .micro-dormitory-treenode
      > .micro-dormitory-tree-checkbox {
      display: none;
    }
    /deep/
      .micro-dormitory-tree
      > .micro-dormitory-tree-list
      > .micro-dormitory-tree-list-holder
      > .micro-dormitory-tree-list-holder-inner
      > .micro-dormitory-treenode
      > .micro-dormitory-tree-checkbox {
      display: none;
    }
  }
  .details {
    width: 480px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    .info {
      height: 46px;
      font-size: 16px;
      line-height: 46px;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      font-weight: 400;
      color: #222222;
      border-bottom: 1px solid #e1dddd;
      padding-left: 16px;
    }
    .info-content {
      height: 32px;
      display: flex;
      align-items: center;
      padding: 24px 24px;
    }
  }
  .detailsStudent {
    width: 622px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    .info {
      height: 46px;
      font-size: 16px;
      line-height: 46px;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      font-weight: 400;
      color: #222222;
      border-bottom: 1px solid #e1dddd;
      padding-left: 16px;
    }
    .info-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
      padding-bottom: 0px !important;
      .checkBox {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        li {
          /deep/ .micro-dormitory-checkbox-wrapper {
            display: flex;
            align-items: center;
          }
          /deep/ .micro-dormitory-checkbox + span {
            display: flex;
            align-items: center;
          }
          width: 180px;
          // margin-right: 40px;
          margin-bottom: 24px;
          img {
            width: 32px;
            height: 32px;
            margin-left: 16px;
            margin-right: 8px;
          }
        }
      }
    }
  }
}
/deep/.micro-dormitory-table-wrapper {
  width: 100%;
}
/deep/.micro-dormitory-tooltip,
/deep/.micro-dormitory-tooltip-placement-topLeft {
  top: -30px !important;
}

/deep/.micro-dormitory-menu-submenu-title {
  overflow: visible;
}

.btn-click {
  // /* 悬浮按钮文字颜色 */
  /deep/.micro-dormitory-btn-primary:hover,
  /deep/.micro-dormitory-btn-primary:focus {
    color: #fff;
  }
}
// 滚动条
&::-webkit-scrollbar {
  width: 6px;
}

&::-webkit-scrollbar-thumb {
  background: rgba(20, 20, 20, 0.2);
  border-radius: 3px;
}

&::-webkit-scrollbar-track {
  background: transparent;
}
.z-tab-box-padding /deep/.micro-dormitory-tabs-nav {
  padding-left: 20px !important;
  box-sizing: border-box;
}
</style>
